#include <iostream>
#include <unordered_map>
#include <vector>
#include <iomanip>

using namespace std;

class Bridge
{
private:
    unordered_map<int, int> macTable; // MAC地址表：MAC -> 端口
    const int BROADCAST = 0xF;        // 广播地址

public:
    // 处理输入帧并输出转发决策
    void processFrame(int srcMac, int srcPort, int destMac)
	{
        // 学习源MAC地址（非广播地址）
        if (srcMac != BROADCAST) macTable[srcMac] = srcPort;

        // 确定目的端口
        int destPort;
        if (destMac == BROADCAST) destPort = -1; // -1表示广播到所有端口（除源端口外）
        else
		{
            auto it = macTable.find(destMac);
            destPort = (it != macTable.end()) ? it->second : -1;
        }

        // 输出处理结果
        cout << "Frame: [" << hex << setw(2) << setfill('0') << srcMac << " -> " << setw(2) << destMac << "] | ";
        
        if (destPort == -1) cout << "Broadcast to all ports (except " << srcPort << ")";
        else if (destPort == srcPort) cout << "Discard (same segment)";
        else cout << "Forward to port " << destPort;
        cout << endl;

        // 打印当前MAC表
        printMacTable();
    }

    // 打印MAC地址表
    void printMacTable()
	{
        cout << "MAC Table: ";
        if (macTable.empty()) cout << "(Empty)";
        else
		{
            for (const auto& entry : macTable)
			{
                cout << hex << setw(2) << setfill('0') << entry.first << "->" << entry.second << " ";
            }
        }
        cout << "\n--------------------------------" << endl;
    }
};

int main()
{
    Bridge bridge;
    vector<tuple<int, int, int>> testFrames = {
        {0x1, 1, 0x3},  // 帧1：从端口1发往0x3（未知单播）
        {0x3, 2, 0x1},  // 帧2：从端口2发往0x1（已知单播）
        {0x2, 1, 0xF},  // 帧3：从端口1广播
        {0x4, 2, 0x2}   // 帧4：从端口2发往0x2（未知单播）
    };

    for (const auto& frame : testFrames)
	{
        bridge.processFrame(get<0>(frame), get<1>(frame), get<2>(frame));
    }

    return 0;
}